//
//  L9Hellper.m
//  Lesson109
//
//  Created by 徐盟 on 2023/3/6.
//

#import "XMHelper.h"

@implementation XMHelper



+(UIColor *) randomColor
{
    CGFloat red = arc4random_uniform(256)/ 255.0;
    CGFloat green = arc4random_uniform(256)/ 255.0;
    CGFloat blue = arc4random_uniform(256)/ 255.0;
    
    return  [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

+ (CGSize) sizeWIthText:(NSString*) text maxSize:(CGSize) maxSize fontSize:(int) fontSize
{
    NSDictionary *attrs = @{NSFontAttributeName: [UIFont systemFontOfSize: fontSize] };
    CGSize size = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    
    return size;
}


/// int转二进制字符串
+ (NSString *)intToBinary:(int)intValue
{
  int byteBlock = 8,    // 每个字节8位
      totalBits = sizeof(int) * byteBlock, // 总位数（不写死，可以适应变化）
      binaryDigit = 1;  // 当前掩（masked）位
  NSMutableString *binaryStr = [[NSMutableString alloc] init];   // 二进制字串
   do
  {
    // 检出下一位，然后向左移位，附加 0 或 1
    [binaryStr insertString:((intValue & binaryDigit) ? @"1" : @"0" ) atIndex:0];
     // 若还有待处理的位（目的是为避免在最后加上分界符），且正处于字节边界，则加入分界符|
      if (--totalBits && !(totalBits % byteBlock)){
          [binaryStr insertString:@"|" atIndex:0];
      }
     // 移到下一位
    binaryDigit <<= 1;
   } while (totalBits);
   // 返回二进制字串
  return binaryStr;
    
}

/// 字节数组转二进制字符串
+(NSString *)byteArrToBinnaryStr:(Byte *)data length:(int)length
{
    char char_1 = '1',char_0 = '0';
    char *chars = malloc(length*8 + length);
    for(int i=0;i<length;i++)
    {
        int offset = i;
        Byte bb = data[i];
        for(int j=0;j<8;j++)
        {
            int idx = i*8+(7-j) +offset;
   
            if(((bb>>j)&0x01) == 1)
            {
                chars[idx] = char_1;
            }else{
                chars[idx] = char_0;
            }
            if (j==7 && i<length-1) {
           
                chars[i*8+offset+8] = ' ';
            }
        }
      
    }
    // 结尾
    chars[length*8+length-1] = 0;
    NSString *string = [NSString stringWithCString:chars encoding:NSUTF8StringEncoding];

    return string;
}

// 二进制转换为十六进制字符串的。
+ (NSString *)hexStringFromData:(NSData *)data
{
    Byte * bytes = (Byte *) [data bytes];
    NSMutableString *hexStr = [NSMutableString string];
    for (int i=0; i<[data length]; i++) {
        NSString * hex = [NSString stringWithFormat:@"%x", bytes[i] & 0xff];
        if([hex length]==1){
            [hexStr appendFormat:@"0%@", hex];
        } else{
            [hexStr appendFormat:@"%@", hex];
        }
    }
    return  hexStr;
}

// 十六进制转换为普通字符串的。
+ (NSString *)stringFromHexString:(NSString *)hexString
{
    if (hexString ==nil) {
        return nil;
    }
    if ([hexString length]==0) {
        return @"";
    }
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        if (anInt>127) {
            anInt = (unsigned int)'?';
        }
        myBuffer[i / 2] = (char)anInt;
    }

    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:NSUTF8StringEncoding];

    return unicodeString;
 
}
 
//普通字符串转换为十六进制的。
 
+ (NSString *)hexStringFromString:(NSString *)string
{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++){
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1){
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        }else{
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
    }
    return hexStr;
}

//NSData转字符串
 
+ (NSString *)stringFromData:(NSData *)data
{
    NSString *hexStr = [self hexStringFromData:data];
    NSString * str = [self stringFromHexString:hexStr];
    
    return str;
}

- (NSData *)dataFromHexString:(NSString *)str {
    
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    return hexData;
}

@end
